<template>
    <div class="user-management">
      <div class="header">
        <h2>用户管理</h2>
        <el-button type="primary" @click="handleAdd" :icon="Plus">
          新增用户
        </el-button>
      </div>
  
      <!-- 搜索区域 -->
      <el-card class="search-card">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="员工姓名">
            <el-input
              v-model="searchForm.employeeName"
              placeholder="请输入员工姓名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset" :icon="Refresh">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 用户列表 -->
      <el-card>
        <el-table
          :data="userList"
          v-loading="loading"
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="username" label="用户名" min-width="120" />
          <el-table-column prop="employeeName" label="员工姓名" min-width="120">
            <template #default="{ row }">
              {{ row.employeeName || '未关联员工' }}
            </template>
          </el-table-column>
          <el-table-column prop="deptName" label="所属部门" min-width="120">
            <template #default="{ row }">
              {{ row.deptName || '未分配部门' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isEnabled ? 'success' : 'danger'">
                {{ row.isEnabled ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                :type="row.isEnabled ? 'warning' : 'success'"
                link
                @click="handleStatusChange(row)"
              >
                {{ row.isEnabled ? '禁用' : '启用' }}
              </el-button>
              <el-button
                size="small"
                type="danger"
                link
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 新增/编辑用户对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="userRules"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="userForm.username"
              placeholder="请输入用户名"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item 
            label="密码" 
            prop="password"
            v-if="!userForm.id"
          >
            <el-input
              v-model="userForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="关联员工" prop="employeeId">
            <el-select
              v-model="userForm.employeeId"
              placeholder="请选择员工"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="employee in employeeList"
                :key="employee.id"
                :label="employee.name"
                :value="employee.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="isEnabled">
            <el-radio-group v-model="userForm.isEnabled">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, nextTick, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Search, Refresh } from '@element-plus/icons-vue'
  import { userApi } from '@/api/user'
  import { employeeApi } from '@/api/employee'
  
  // 响应式数据
  const loading = ref(false)
  const dialogVisible = ref(false)
  const submitting = ref(false)
  const userFormRef = ref()
  const userList = ref([])
  const employeeList = ref([])
  
  // 搜索表单
  const searchForm = reactive({
    username: '',
    employeeName: ''
  })
  
  // 分页数据
  const pagination = reactive({
    page: 1,
    size: 10,
    total: 0
  })
  
  // 用户表单
  const userForm = reactive({
    id: null,
    username: '',
    password: '',
    employeeId: null,
    isEnabled: 1
  })
  
  // 表单验证规则
  const userRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
    ],
    password: [
      { 
        required: true, 
        message: '请输入密码', 
        trigger: 'blur',
        validator: (rule, value, callback) => {
          if (!userForm.id && !value) {
            callback(new Error('请输入密码'))
          } else if (value && (value.length < 6 || value.length > 50)) {
            callback(new Error('密码长度在 6 到 50 个字符'))
          } else {
            callback()
          }
        }
      }
    ],
    employeeId: [
      { required: true, message: '请选择员工', trigger: 'change' }
    ]
  }
  
  // 计算属性
  const dialogTitle = computed(() => {
    return userForm.id ? '编辑用户' : '新增用户'
  })
  
  // 加载用户列表 - 根据实际响应格式修复
  const loadUserList = async () => {
    try {
      loading.value = true
      
      const params = {
        ...searchForm,
        page: pagination.page,
        size: pagination.size
      }
      
      const response = await userApi.getUserList(params)
      console.log('API响应:', response)
      
      // 根据实际响应格式处理数据
      if (response && response.code === 1) { // 注意：这里code是1，不是200
        if (response.data && response.data.rows) {
          userList.value = response.data.rows
          pagination.total = response.data.total
          console.log('用户列表加载成功:', userList.value.length, '条记录')
        } else {
          userList.value = []
          pagination.total = 0
          ElMessage.warning('暂无用户数据')
        }
      } else {
        ElMessage.error(response?.msg || '获取用户列表失败')
      }
    } catch (error) {
      console.error('获取用户列表错误:', error)
      ElMessage.error(error.message || '获取用户列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 加载员工列表
  const loadEmployeeList = async () => {
    try {
      const response = await employeeApi.getAllEmployees()
      if (response && response.code === 1) {
        employeeList.value = response.data?.rows || response.data || []
      }
    } catch (error) {
      console.error('加载员工列表错误:', error)
    }
  }
  
  // 其他方法保持不变...
  const handleSearch = () => {
    pagination.page = 1
    loadUserList()
  }
  
  const handleReset = () => {
    Object.assign(searchForm, {
      username: '',
      employeeName: ''
    })
    pagination.page = 1
    loadUserList()
  }
  
  const handleAdd = () => {
    Object.assign(userForm, {
      id: null,
      username: '',
      password: '',
      employeeId: null,
      isEnabled: 1
    })
    dialogVisible.value = true
    nextTick(() => {
      userFormRef.value?.clearValidate()
    })
  }
  
  const handleEdit = (row) => {
    Object.assign(userForm, {
      id: row.id,
      username: row.username,
      password: '',
      employeeId: row.employeeId,
      isEnabled: row.isEnabled
    })
    dialogVisible.value = true
    nextTick(() => {
      userFormRef.value?.clearValidate()
    })
  }
  
  const handleSubmit = async () => {
    try {
      const valid = await userFormRef.value.validate()
      if (!valid) return
  
      submitting.value = true
      
      if (userForm.id) {
        const { password, ...updateData } = userForm
        const submitData = password ? { ...userForm } : updateData
        await userApi.updateUser(submitData)
        ElMessage.success('更新用户成功')
      } else {
        await userApi.addUser(userForm)
        ElMessage.success('新增用户成功')
      }
      
      dialogVisible.value = false
      loadUserList()
    } catch (error) {
      ElMessage.error(error.response?.data?.message || error.message || '操作失败')
    } finally {
      submitting.value = false
    }
  }
  
  const handleStatusChange = async (row) => {
    try {
      const newStatus = row.isEnabled ? 0 : 1
      const action = newStatus ? '启用' : '禁用'
      
      await ElMessageBox.confirm(
        `确定要${action}用户 "${row.username}" 吗？`,
        '提示',
        { type: 'warning' }
      )
      
      await userApi.updateUserStatus(row.id, newStatus)
      ElMessage.success(`${action}用户成功`)
      loadUserList()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error.response?.data?.message || error.message || '操作失败')
      }
    }
  }
  
  const handleDelete = async (row) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除用户 "${row.username}" 吗？此操作不可恢复！`,
        '警告',
        {
          type: 'warning',
          confirmButtonText: '确定删除',
          cancelButtonText: '取消'
        }
      )
      
      await userApi.deleteUser(row.id)
      ElMessage.success('删除用户成功')
      loadUserList()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error.response?.data?.message || error.message || '删除用户失败')
      }
    }
  }
  
  const handleSizeChange = (size) => {
    pagination.size = size
    pagination.page = 1
    loadUserList()
  }
  
  const handleCurrentChange = (page) => {
    pagination.page = page
    loadUserList()
  }
  
  const formatTime = (time) => {
    if (!time) return ''
    return new Date(time).toLocaleString()
  }
  
  onMounted(() => {
    loadUserList()
    loadEmployeeList()
  })
  </script>
  
  <style scoped>
  .user-management {
    padding: 20px;
  }
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  :deep(.el-table .cell) {
    white-space: nowrap;
  }
  </style>